package com.cskaoyan.config;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author ：SZ HIT LYC
 * @description:
 * @date ：2022/5/8 23:32
 */
public class CustomAuthenticator extends ModularRealmAuthenticator {
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        this.assertRealmsConfigured();
        Collection<Realm> allRealms = this.getRealms();

        MallToken token = (MallToken) authenticationToken;
        String type = token.getType();
        List<Realm> realms = new ArrayList<>();
        for (Realm allRealm : allRealms) {
            if(allRealm.getName().toLowerCase().contains(type)){
                realms.add(allRealm);
            }
        }

        return realms.size() == 1 ? this.doSingleRealmAuthentication((Realm)realms.iterator().next(), authenticationToken) : this.doMultiRealmAuthentication(realms, authenticationToken);
    }
}
